/**
 *
 * @author Ryan Thomas <s548169@sbuniv.edu>
 */

package guichatclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class InputThread extends Thread{
    
    protected Controller control;
    private  OptionHandler chatOptions;
    private FRMChat mainFrame;
    
    /**
     * 
     * @param control
     * @param chatOptions
     * @param mainFrame 
     */
    
    public InputThread(Controller control, OptionHandler chatOptions, FRMChat mainFrame){
        this.control = control;
        this.chatOptions = chatOptions;
        this.mainFrame = mainFrame;
    }
    
    /**
     * 
     */
    
    public void test(){
        System.out.println(mainFrame);
    }
    
    /**
     * 
     */
    
    @Override
    public void run(){
        try {
            String input;
            String killedby="";
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(chatOptions.getConnection().getInputStream()));
            while (control.get()){
                input = inFromServer.readLine();//Read from server
                if(input.equalsIgnoreCase("SVR:RPLY:TERM-OKAY")) {
                    control.disable();
                }
                else if(input.equalsIgnoreCase("SVR:SEND:TERM")){
                        control.disable();
                        killedby="server";
                }
                else{
                        System.out.println(input);
                        mainFrame.writeToScreen(input);
                }
            }
            chatOptions.getConnection().close();
            if(killedby.equals("server")) {
                System.out.println("Connection Terminated. Press Enter to End");
            }
        } catch (IOException ex) {
            try {
                if(ex.getMessage()==null || ex.getClass()== java.net.SocketException.class){
                    System.out.println("Server Disconnect. Press Enter to end program.");
                    chatOptions.getConnection().shutdownInput();
                }
                else {
                    System.out.println(ex.getMessage());
                }
            } catch (IOException ex1) {
                System.out.println(ex.getMessage());
            }
        }catch (NullPointerException ex) {
            System.out.println(ex.getMessage());
            throw ex;
        }
    }
}
